package com.shiyi.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author wangzhanshuai
 * @date 2021/1/23 12:07 下午
 * @since 1.0
 */
@Controller
public class DownloadController {

    @RequestMapping("download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) {
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/images/121.jpg");
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(realPath);
            byte[] bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            //将要下载文件内容返回
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.set("Content-Disposition","attachment;filename=121.jpg");
            return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        } catch (FileNotFoundException e) {
            System.out.println("文件找不到 e: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("读取文件失败 e: " + e.getMessage());
        } finally {
            if(fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
    }
}
